package com.knowledge.plus.自定义异常;

import com.alibaba.fastjson.JSONObject;
import com.knowledge.plus.自定义异常.enums.CommonEnum;
import com.knowledge.plus.自定义异常.service.BaseErrorInfoInterface;
import lombok.Data;

/**
 * 自定义数据格式
 *
 * @author PF.Tian
 * @since 2021/09/13
 */
@Data
public class ResultBody {

    /* 响应代码 */
    private String code;

    /* 响应消息 */
    private String message;

    /* 响应结果 */
    private Object result;

    /**
     * 成功
     */
    public static ResultBody success() {
        return success(null);
    }

    /**
     * 成功，带返回体
     */
    public static ResultBody success(Object data) {
        ResultBody rb = new ResultBody();
        rb.setCode(CommonEnum.SUCCESS.getResultCode());
        rb.setMessage(CommonEnum.SUCCESS.getResultMsg());
        rb.setResult(data);
        return rb;
    }

    /**
     * 失败，带错误编号和错误消息
     */
    public static ResultBody error(BaseErrorInfoInterface errorInfo) {
        return error(errorInfo.getResultCode(), errorInfo.getResultMsg());
    }

    /**
     * 失败，带错误编号和错误消息
     */
    public static ResultBody error(String code, String message) {
        ResultBody rb = new ResultBody();
        rb.setCode(code);
        rb.setMessage(message);
        rb.setResult(null);
        return rb;
    }

    /**
     * 失败，默认错误编号-1，带错误消息
     */
    public static ResultBody error(String message) {
        ResultBody rb = new ResultBody();
        rb.setCode("-1");
        rb.setMessage(message);
        rb.setResult(null);
        return rb;
    }

    @Override
    public String toString() {
        return JSONObject.toJSONString(this);
    }

}
